import {Row, Col, Input, Modal, Pagination, Button, Dropdown, Icon, Form, message} from 'antd';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Input from '../../../_antd1.11.2/Input';
// import Modal from '../../../_antd1.11.2/Modal';
// import Pagination from '../../../_antd1.11.2/pagination';
// import Button from '../../../_antd1.11.2/Button';
// import Dropdown from '../../../_antd1.11.2/Dropdown';
// import Icon from '../../../_antd1.11.2/Icon';
// import Form from '../../../_antd1.11.2/Form'
const FormItem = Form.Item;
// import message from '../../../_antd1.11.2/message'
import cloneDeep from 'lodash/cloneDeep';
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty'
import uniq from 'lodash/uniq'
import isEqual from 'lodash/isEqual';

import WeaInputSearch from '../../wea-input-search';
import WeaSearchBrowserBox from '../wea-search-browser-box';
import WeaAssociativeSearchMult from '../wea-associative-search-mult'
import WeaTools from '../../wea-tools';
import Thumbnail from './thumbnail';
import WeaSearchAdvance from '../../wea-search-advance';
import PureRenderMixin from 'react-addons-pure-render-mixin';

const initialState = {
    showSearchAd:false,
    count: 0,
    visible: false,
    currentPage: 1,
    inputValue: '',
    searchPara: {},
    browserConditions: [],
}

class Main extends React.Component {
    static defaultProps = {
        mult:true,
    }
    constructor(props) {
        super(props);
        this.state = {
            visible: null,
            initialShowSearchAd:false,
            showSearchAd:false,
            isClearData: false,
            selectedData: {}, // 搜索按钮选中的数据
            listDatas: [],
            currentPage: 1,
            pageSize: 20,
            count: 0,
            url: props.dataUrl,
            inputValue: '',
            searchPara: {},
            dataKey:'',
            inputId: '',
            inputName: '',
            browserConditions: [],
            contentType: 1, // 数据展示的类别
            quickSearch: '',
            hiddenIds:'',
            thumbnails:[],
            ctrIds:[],//check id受控
            ctrDatas:[],
        }
    }
    componentDidMount() {
        // 默认显示数据
        if (!isEmpty(this.props.replaceDatas)) {
            this.replaceSearchValues(this.props.replaceDatas);
        }
    }
    shouldComponentUpdate(...args) {
        return PureRenderMixin.shouldComponentUpdate.apply(this, args);
    }
    componentWillReceiveProps(nextProps){
        if (this.props.value !== nextProps.value && isEmpty(nextProps.value)) {
            this.setState({isClearData: !this.state.isClearData});
            this.handleClear();
        }
        if (!isEqual(this.props.replaceDatas, nextProps.replaceDatas)) {
            this.replaceSearchValues(nextProps.replaceDatas);
        }
    }
    datakeyTodatas(newDataKey,newCurrent,min,max,cb) {
        WeaTools.callApi("/api/ec/dev/table/datas", 'POST', {dataKey: newDataKey, min: min, max: max}).then(data => {
            if (cb) cb();
            this.setState({
                listDatas: data.datas,
                thumbnails:data.browser,
            });
        }, (e) => {
            console.log('api /api/ec/dev/table/datas error', e)
        }),
        WeaTools.callApi("/api/ec/dev/table/counts",'POST',{ dataKey: newDataKey }).then(data => {
            this.setState({
                count: data.count,
            });
        }, (e) => {
            console.log('api /api/ec/dev/table/counts error', e)
        })
    }
    formatUrl(url, params) {
        if (url && !isEmpty(params)) {
            url = `${url}${WeaTools.getFd(params)}`;
        }
        return url;
    }
    getData(url, currentPage, hasPagination = false, searchPara, cb) {
        const {pageSize, count} = this.state;
        url = url || this.state.url;
        let params = searchPara || this.state.searchPara || {};
        params = {...params};
        currentPage = currentPage || this.state.currentPage;
        if (hasPagination) {
            params['min'] = (currentPage - 1) * pageSize + 1;
            params['max'] = currentPage * pageSize;
        }
        if(params['max'] && currentPage > 1) {
            if (params['max'] > count) params['max'] = count;
        }
        WeaTools.callApi(this.formatUrl(url, params),'GET').then(data=> {
            if (data.type == 1){//分页table
                const dataKey = data.datas;
                this.setState({
                    contentType: data.type,
                });
                this.datakeyTodatas(dataKey,currentPage,params['min'],params['max'], cb);
            }
        }).catch(error=>{
            message.err(error);
        })
    }
    onPageChange(page) {
        this.getData('', page, true);
        this.setState({currentPage: page});
    }
    onSearchChange(v){
        const {tabs} = this.props;
        const quickSearch = this.state.quickSearch || 'name';
        const {dataUrl} = this.props;
        const {setFieldsValue} = this.props.form;
        let params = {};
        params[quickSearch] = v;
        if (!isEmpty(tabs) && !isEmpty(tabs[0].dataParams)) {
            params = {...params, ...tabs[0].dataParams};
        }
        this.getData(dataUrl, 1, true, params); // 搜索获取数据
        setFieldsValue(params); // 高级搜索数据联动
        this.setState({
            url: dataUrl,
            inputValue: v,
            showSearchAd: false,
            searchPara: params,
        });
    }
    goSearch=(e)=>{
        const {tabs} = this.props;
        const quickSearch = this.state.quickSearch || 'name';
        const {dataUrl} = this.props;
        e.preventDefault();
        const {validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                message.error('Errors in form!!!');
                return;
            }
            let newObject = cloneDeep({...object,...conditionParamsBK});
            forEach(newObject, (value, key) => {
                if (value) params[key] = value;
            })
        });
        if (!isEmpty(tabs) && !isEmpty(tabs[0].dataParams)) {
            params = {...params, ...tabs[0].dataParams};
        }
        this.getData(dataUrl, 1, true, params); // 搜索获取数据
        this.setState({
            url: dataUrl,
            searchPara: params,
            showSearchAd:false,
            inputValue: params[quickSearch] || '',
        });
    }
    showModal() {
        this.setState({visible: true});
    }

    setShowSearchAd(bool){
        const {showSearchAd}=this.state;
        this.setState({showSearchAd:bool, initialShowSearchAd:true})
    }
    onCustomClick = (e) => {
        e.preventDefault();
        this.onBrowerClick();
    }
    onBrowerClick = (keys, selectedObj) => {
        const {resetFields, setFieldsValue} = this.props.form;
        resetFields(); // 重置高级搜索
        const {tabs, dataUrl} = this.props;
        let url = dataUrl;
        if (isEmpty(keys)) {
            this.setState({ctrDatas: []});
        }
        const {conditionURL} = this.props;
        WeaTools.callApi(conditionURL,'GET').then(data=>{
            let quickSearch;
            if (!isEmpty(data.conditions)) {
                data.conditions.forEach((item)=> {
                    if (item.isQuickSearch) {
                        quickSearch = item.domkey[0];
                    }
                })
            }
            const params = WeaTools.getParamsByConditions(data.conditions);
            conditionParamsBK = params;
            setFieldsValue(params);
            this.browserConditionsBk = data.conditions;
            this.defaultConditionParams = {...params};
            this.setState({
                browserConditions: data.conditions,
                quickSearch, url,
                searchPara: params,
                inputValue: params[quickSearch] || '',
            });
            this.getData(url, 1, true, params, ()=> {
                // reset selected data
                if (!isEmpty(keys)) {
                    this.onBrowerChangeHandler(keys, selectedObj);
                }
            });
        });
        this.showModal();
    }
    handleOk() {
        const {ctrIds,ctrDatas} = this.state;
        let selectedData = {};
        for(let i=0; i< ctrIds.length; i++) {
            selectedData[ctrIds[i]] = ctrDatas[i];
        }
        this.setState({
            ctrIds:ctrIds,
            ctrDatas:ctrDatas,
            selectedData:selectedData,
            visible: false,
        })
        // console.log(2, ctrIds, selectedData, ctrDatas);
        this.throwCurrentState(ctrIds.join(','), ctrDatas);
        this.setState(initialState);//初始化浏览框
    }
    handleCancel() {
        this.setState(initialState);//初始化浏览框
    }
    handleClear() {
        this.setState({
            visible: false,
            isClearData: !this.state.isClearData,
            selectedData: {},
            ctrIds:[],
            ctrDatas:[],
        });
        this.setState(initialState);//初始化浏览框
        this.throwCurrentState('', []);
    }
    replaceSearchValues(datas = []) {
        let ctrIds = [], selectedData = {};
        datas.forEach((item) => {
            ctrIds.push(item.id);
            selectedData[item.id] = item;
        })
        this.setState({ctrIds:ctrIds, ctrDatas:datas, selectedData: selectedData});
    }
    toArr(values,datas){
        let arr = [];
         for(let i=0; i< values.length; i++) {
           arr.push(datas[values[i]])
        }
        return arr;
    }
    onBrowerChangeHandler(values, datas) {
        const {ctrIds,ctrDatas} = this.state;

        const throwDatas = this.toArr(values,datas);
        this.setState({
            ctrIds:values,
            ctrDatas:throwDatas,
            selectedData: datas
        });
        this.throwCurrentState(values.join(','), throwDatas);
    }
    count(ctrIds = [], rNum = false) {
        const {inputId = 'id'} = this.state;
        let count = 0;
        count += uniq(ctrIds).length;
        if (rNum) return count;
        return count > 0 ? `(${count})` : '';
    }

    thumbnailsOnCheck(ids, datas) {
        // console.log('thumbnailsOnCheck===',ids,'datas',datas)
        this.setState({
            ctrIds:ids,
            ctrDatas:datas,
        })
    }
    render() {
        const {icon,iconBgcolor,title,browerType,dataUrl,min,max,fieldName,contentHeight, modalStyle}=this.props;
        const {id,name,style,isMult,disabled,value,type,mult,customized} = this.props;
        const {visible,showSearchAd, listDatas, inputValue, pageSize, count, currentPage} = this.state;
        const {displayType,selectedData,ctrIds,ctrDatas} = this.state;
        const {inputId, inputName,  contentType, treeData, hiddenIds} = this.state;
        let titleEle = (
            <Row>
                <Col span="8" style={{paddingLeft:20,lineHeight:'48px'}}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ? <div className="wea-workflow-radio-icon-circle" style={{background:iconBgcolor ? iconBgcolor : ""}}><i className={icon}/></div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>}
                        <span style={{verticalAlign:'middle'}}>{title}</span>
                    </div>
                </Col>
            </Row>
        );
        let inputArr = (
            <WeaAssociativeSearchMult
                {...this.props}
                inputName={inputName}
                inputId={inputId}
                style={this.props.inputStyle}
                datas={selectedData}
                selectedValues={ctrIds}
                isClearData={this.state.isClearData}
                type={type}
                clickCallback={this.onBrowerClick}
                onChange={this.onBrowerChangeHandler.bind(this)}
            />
        );
        const buttons = [
                <Button key="submit" type="primary" size="large" onClick={this.handleOk.bind(this) } disabled={this.count(ctrIds, true) == 0}>确 定{this.count(ctrIds)}</Button>,
                <Button key="clear" type="ghost" size="large" onClick={this.handleClear.bind(this)}>清 除</Button>,
                <Button key="back" type="ghost" size="large" onClick={this.handleCancel.bind(this)}>取 消</Button>];
        const searchsBox = this.getSearchs();
        const buttonsAd = this.getTabButtonsAd();
        let sheight = initHeight = contentHeight;
        if (contentType === 1 || contentType === 4 ) sheight -= 35; //显示分页
        const {dataKey} = this.state;
        let dom = inputArr;
        if (customized) {
            dom = (
                <div className="cursor-pointer" onClick={this.onCustomClick}>
                    {this.props.children}
                </div>
            )
        }
        const browserPagination =(
            <Pagination
                weaSimple
                showTotal={total => `共${total}条`}
                total={count}
                pageSize={pageSize}
                current={currentPage}
                onChange={this.onPageChange.bind(this)}
            />
        );
        return (
          <div>
            {dom}
            <input type="hidden" id={fieldName} name={fieldName} value={hiddenIds} />
            <Modal wrapClassName="wea-hr-muti-input wea-browser-thumbnails"
              title={titleEle}
              width={modalStyle.width}
              maskClosable={false}
              visible={visible}
              onCancel={this.handleCancel.bind(this)}
              footer={buttons}>
            <div className='wea-thumbnails'>
                <Thumbnail
                    {...this.props}
                    sheight={sheight}
                    tableDatas={this.state.listDatas}
                    browser={this.state.thumbnails}
                    ctrIds={uniq(this.state.ctrIds)}
                    ctrDatas={this.state.ctrDatas}
                    thumbnailsOnCheck={this.thumbnailsOnCheck.bind(this)}
                >    <WeaSearchAdvance
                        buttonsAd={buttonsAd}
                        searchType={['base','advanced']}
                        searchsBaseValue={inputValue}
                        searchsAd={<Form horizontal>{searchsBox}</Form>}
                        showSearchAd={showSearchAd}
                        setShowSearchAd={(bool)=>{this.setShowSearchAd(bool)}}
                        onSearchChange={(v)=> this.setState({inputValue: v})}
                        onSearch={this.onSearchChange.bind(this)}
                    />
                </Thumbnail>
                {browserPagination}
                </div>
            </Modal>
          </div>
        );
    }
    throwCurrentState(ids, datas = []){
        ids = uniq(ids.split(',')).join(',');
        this.setState({hiddenIds: ids});
        let names = [];
        datas.forEach((d) => {
            names.push(d.name);
        });
        this.props.onChange && this.props.onChange(ids, names.join(','), datas);
    }

    getSearchs(){
        const {browserConditions} = this.state;
        let items = [];
        !isEmpty(browserConditions)&& browserConditions.forEach( field => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey,this.props, field)}
                    </FormItem>),
                colSpan: 1
            });
        });
        return <WeaSearchBrowserBox  items={items} />
    }

    getTabButtonsAd() {
        let _this = this;
        const {resetFields,validateFields} = this.props.form;
        return [
            <Button type="primary" onClick={(e)=>{this.goSearch(e)}}>搜索</Button>,
            <Button type="ghost" onClick={(e)=>{e.preventDefault(); this.setState({inputValue: ''}); resetFields()}}>重置</Button>,
            <Button type="ghost" onClick={()=>{_this.setState({showSearchAd:false})}}>取消</Button>
        ]
    }
}

let conditionParamsBK={};
Main = Form.create({
    onFieldsChange(props, fields){
        for(let key in fields) {
            conditionParamsBK[fields[key].name] = fields[key].value
        }
    }
})(Main);
export default Main;